import React, { useEffect, useState } from 'react'; // 导入React和hooks
import { Table, Card, Tag, Button, Popconfirm, message, Space } from 'antd'; // 导入Antd组件

// 假设有全局用户信息
const getCurrentUserRole = () => {
  // 真实项目可从store或context获取
  return localStorage.getItem('role') || 'employee'; // 'admin' or 'employee'
};

const ProductManagement = () => {
  const [products, setProducts] = useState([]); // 商品数据
  const [loading, setLoading] = useState(true); // 加载状态
  const role = getCurrentUserRole();

  // 获取商品数据
  const fetchProducts = async () => {
    setLoading(true);
    const res = await fetch('http://localhost:3001/api/products');
    const data = await res.json();
    setProducts(data);
    setLoading(false);
  };

  useEffect(() => {
    fetchProducts();
  }, []);

  // 删除商品
  const deleteProduct = async (id) => {
    const res = await fetch(`http://localhost:3001/api/products/${id}`, {
      method: 'DELETE'
    });
    const data = await res.json();
    if (data.success) {
      message.success('商品已删除');
      fetchProducts();
    } else {
      message.error(data.error || '删除失败');
    }
  };

  // 表格列
  const columns = [
    { title: '商品名称', dataIndex: 'name', key: 'name' },
    { title: '分类', dataIndex: 'category', key: 'category' },
    { title: '单价', dataIndex: 'price', key: 'price', render: v => `¥${v}` },
    { title: '库存', dataIndex: 'stock', key: 'stock', render: stock => <Tag color={stock > 0 ? 'blue' : 'red'}>{stock}</Tag> },
    { title: '今日销量', dataIndex: 'todaySales', key: 'todaySales', render: v => <Tag color="green">{v}</Tag> },
    {
      title: '操作',
      key: 'action',
      render: (_, record) =>
        role === 'admin' ? (
          <Popconfirm
            title="确定要删除该商品吗？"
            onConfirm={() => deleteProduct(record._id)}
            okText="确定"
            cancelText="取消"
          >
            <Button danger size="small">删除/下架</Button>
          </Popconfirm>
        ) : null
    }
  ];

  // 公共卡片样式，和库存管理页面保持一致
  const cardStyle = {
    maxWidth: 1100, // 最大宽度
    margin: '0 auto', // 居中
    boxShadow: '0 4px 24px rgba(99,102,241,0.08)', // 阴影
    borderRadius: 18, // 圆角
    background: '#fff', // 白色背景
    padding: '24px 32px' // 内边距
  };

  return (
    <Card
      title={<span style={{ fontWeight: 700, fontSize: 22, letterSpacing: 1 }}>商品管理</span>}
      style={cardStyle}
      headStyle={{ borderBottom: '1px solid #f0f0f0', background: 'transparent', marginBottom: 16 }}
      bodyStyle={{ padding: 0 }}
    >
      <Table
        columns={columns}
        dataSource={products}
        rowKey="_id"
        loading={loading}
        pagination={{ pageSize: 10 }}
        scroll={{ x: 'max-content' }}
        bordered
      />
    </Card>
  );
};

export default ProductManagement; // 导出页面 